var express = require("express");
var router = express.Router();
var user = require("../../models/webSite/user");
var md5 = require("md5");
var isLogin = require("./public/is-login.js");
//判断是否登录
router.get("/login" , isLogin.checkNotLogin);
router.get("/login" , function(req , res){
	res.render("webSite/login" , {
		title : "欢迎来到登录页"
	});
});
router.post("/login" , isLogin.checkNotLogin);
//登录
router.post("/login" , function(req , res){
	var userInfo = req.body,
		password = md5(userInfo.password),
		userFun = new user();
	if(!userInfo.name){
		return res.json({
			state : "error",
			message : "请输入用户名"
		});
	};
	if(!userInfo.password){
		return res.json({
			state : "error",
			message : "请输入密码"
		});
	};
	userFun.getUser(userInfo.name , function(err , data){
		if(err){
			return res.json({
				state : "error",
				message : err
			});
		};
		if(!data){
			return res.json({
				state : "error",
				message : "用户名或密码不正确"
			});
		};
		if(password == data.password){
			req.session.user = data;
			return res.json({
				state : "ok",
				message : "登录成功"
			});
		}else{
			return res.json({
				state : "error",
				message : "用户名或密码不正确"
			});
		};
	})
});
//退出登录
router.get("/logout" , function(req , res){
	req.session.user = null;
	res.redirect("/");
})
//接口
module.exports = router;
